package com.bobo.serviceorder.service.impl;

import com.bobo.serviceorder.service.GrabService;
import com.bobo.serviceorder.service.OrderService;
import org.redisson.Redisson;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author bobo
 * @date 2021-04-14
 */
@Service
public class GrabRedissonRedLockServiceImpl implements GrabService {

    @Autowired
    private Redisson redisson1;
    @Autowired
    private Redisson redisson2;
    @Autowired
    private Redisson redisson3;

    @Autowired
    private OrderService orderService;

    @Override
    public String grabOrder(int orderId, int driverId) {
        String lockKey = "lock_" + orderId;
        RLock lock1 = redisson1.getLock(lockKey.intern());
        RLock lock2 = redisson2.getLock(lockKey.intern());
        RLock lock3 = redisson3.getLock(lockKey.intern());
        RedissonRedLock redissonRedLock = new RedissonRedLock(lock1, lock2, lock3);
        boolean b = false;
        try {
            redissonRedLock.lock();
            b = orderService.grabOrder(orderId, driverId);
            if (b) {
                System.out.println("枪单成功！-----red lock");
            } else {
                System.out.println("枪单失败！------red lock");
            }
        } finally {
            redissonRedLock.unlock();
        }
        return b ? "枪单成功" : "枪单失败";
    }
}
